package com.example.iorder.user;

//import java.util.ArrayList;
//import java.util.List;
//
//import org.apache.http.NameValuePair;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.message.BasicNameValuePair;
//import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


//import com.example.domain.OrderedMenuItem;
//import com.example.domain.User;
//import com.example.domain.Restaurant;
import com.example.iorder.R;
import com.example.iorder.config.Config;
//import com.example.iorder.restaurant.MenuItemDetails;
//import com.example.iorder.restaurant.showMenuCard;
import com.example.iorder.util.HTTPClient;
import com.example.iorder.util.MessageManager;
import com.example.iorder.util.DataStorage;

public class RegisterUser extends Activity{
	private ProgressDialog progress;
	boolean userRegisteredSuccesfull = false;
	

	
	
	
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		this.setTitle("Registreren");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_user);	
		progress = new ProgressDialog(this);
	
	
	
	}
	
	public void registerUser(View view){
	
		startLoadingIndicator();
		
		
		TextView lPhoneNumber = (TextView) findViewById(R.id.phoneNumber);
		TextView lPassword= (TextView) findViewById(R.id.password);
		TextView lCheckPassword = (TextView) findViewById(R.id.checkPassword);
		 
		final String phoneNumber = lPhoneNumber.getText().toString();
		final String password = lPassword.getText().toString();
		String checkPassword = lCheckPassword.getText().toString();
		
		if(phoneNumber.equals("")){
			stopLoadingIndicator();
			//Toast.makeText(this, "Een van de velden zijn leeg!", Toast.LENGTH_SHORT).show();
			String errorMessage = "Controleer of u de velden allemaal heeft ingevuld!";
			Drawable image = getResources().getDrawable(R.drawable.error_2);
			View layout = MessageManager.getMessageView(getLayoutInflater(), image, errorMessage);
			
			Toast messageView = new Toast(getApplicationContext());
			messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			messageView.setDuration(Toast.LENGTH_SHORT);
			messageView.setView(layout);
			messageView.show();
			// progress.dismiss();
			// foutmelding
			//showDialog(null, "Foute gegevens!");
	
		}
		
		if (checkPassword.equals(password) && !phoneNumber.equals("") && !password.equals(""))
		{
			
			new Thread() {
				public void run() {
					Message msg = new Message();
	        		String path = "";
	        		HTTPClient httpClient = null;
	        		String searchResult = "";
	        		String postData = "";
	        		
	        	
	        		
	        		// First send request to add reservation
					// Get the user id, table id, date and time 
	        
	        		try {
	        			path = Config.URL_USERS;
	        			httpClient = new HTTPClient(getBaseContext());
	        			postData = ""
	        					+ "{"
	        					+ "\"Firstname\": \"\","
	        					+ "\"Lastname\":\"\"," 
	        					+ "\"City\":\"\"," 
	        					+ "\"PhoneNumber\": \"" + phoneNumber + "\","
	        					+ "\"EmailAddress\": \"\","
	        					+ "\"Password\": \"" + password + "\""
	        					+ "}";
	        			searchResult = httpClient.sendPOSTRequest(Config.IORDER_SERVER, path, postData);
	        			msg.getData().putString("RegistrationDetails", searchResult);
	        			
	        			userOutputHandler.sendMessage(msg);
//	        			JSONObject jsonObject = new JSONObject(searchResult);
//	        			
//	        			if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
//	    					// Connection to server was successful and data was received
//	    					if (jsonObject.get("status").toString().equals("200")) {
//	    						// Get the new reservation id
//	    						
//	    						userRegisteredSuccesfull = true;
//	    					}
//	        			}
	        		} catch (Exception e) {
	        			Log.e("Error while sending information!", e.getMessage());
	        		}
				}
			}.start();
			
				
				
			
			

			
		}else if (!checkPassword.equals(password)){
			stopLoadingIndicator();
			//Toast.makeText(this, "Wachtwoorden komen niet overeen!", Toast.LENGTH_SHORT).show();
			String errorMessage = "Wachtwoorden komen niet overeen!";
			Drawable image = getResources().getDrawable(R.drawable.error_2);
			View layout = MessageManager.getMessageView(getLayoutInflater(), image, errorMessage);
			
			Toast messageView = new Toast(getApplicationContext());
			messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			messageView.setDuration(Toast.LENGTH_SHORT);
			messageView.setView(layout);
			messageView.show();
			}
		
		else {}
		
		
		
		
	}
	private Handler userOutputHandler = new Handler() {
		public void handleMessage(Message msg) 
		{
			stopLoadingIndicator();
			String newData = msg.getData().getString("RegistrationDetails");
			//JSONObject records = null;
			
			try {
				JSONObject jsonObject = new JSONObject(newData);
				if (jsonObject.has("data") && jsonObject.has("msg") && jsonObject.has("status")) 
				{
					// Connection to server was successful and data was received 
					if (jsonObject.get("status").toString().equals("200")) 
					{
						DataStorage dataStorage = DataStorage.getInstance(getApplicationContext());
						
						JSONObject lData = jsonObject.getJSONObject("data");
						String lID = lData.getString("ID");
						String lPhoneNumber = lData.getString("PhoneNumber");
						
						dataStorage.saveStringElement("id", lID);
						dataStorage.saveStringElement("phonenumber", lPhoneNumber);					
						
						
						String errorMessage = "Succesvol geregistreerd";
						Drawable image = getResources().getDrawable(R.drawable.checkmark_green_2);
						View layout = MessageManager.getMessageView(getLayoutInflater(), image, errorMessage);
						
						Toast messageView = new Toast(getApplicationContext());
						messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						messageView.setDuration(Toast.LENGTH_SHORT);
						messageView.setView(layout);
						messageView.show();

						finish();
						return;
					} 
					else 
					{
						String returnValue = jsonObject.get("msg").toString();
						if (returnValue.toLowerCase().contains("duplicate"))
						{
							stopLoadingIndicator();
							Toast.makeText(getBaseContext(), "Login mislukt, gebruiker bestaat al!" , Toast.LENGTH_SHORT).show();
						}
						else
						{
							stopLoadingIndicator();
							Toast.makeText(getBaseContext(), "Backend server error msg: "+ returnValue, Toast.LENGTH_SHORT).show();
					}
					}
						
						// Update the GUI
						
					}else {
						stopLoadingIndicator();

						Toast.makeText(getBaseContext(), "Backend server error no : " + jsonObject.get("status").toString(), Toast.LENGTH_SHORT).show();
						
					}
			} catch (JSONException jsnE) {
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				if (newData.equals("Error: No network")) {
					stopLoadingIndicator();
					errorMessage = getResources().getString(R.string.no_network_connection);
				}
				Toast.makeText(getBaseContext(), errorMessage, Toast.LENGTH_LONG).show();
				
			} catch (Exception e) {
				Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
				
			}
		}
	};
	private void startLoadingIndicator() {
		progress.setTitle(getResources().getString(R.string.loading_title));
        progress.setMessage(getResources().getString(R.string.sending_reservation));
        progress.show();
	}
	
	private void stopLoadingIndicator() {
		progress.dismiss();
	}
		
	
	
	
}